package leecode.LinkedList.DoublePoint;

/**
 * 给你两个单链表的头节点 headA 和 headB ，请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点，返回 null 。
 * 题解：https://leetcode-cn.com/problems/intersection-of-two-linked-lists/solution/xiang-jiao-lian-biao-by-leetcode-solutio-a8jn/
 */
public class GetIntersectionNode {
      public class ListNode {
      int val;
      ListNode next;
      ListNode(int x) {
          val = x;
          next = null;
      }
  }
    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        //A、B任意一个头结点为空，则不可能相交
        if(headA == null || headB == null){
            return null;
        }
        ListNode pA = headA;
        ListNode pB = headB;

        while(pA!=pB){
            /**
             *这里不能写成 if(pA.next!=null){pA = pA.next}else{pA=headB}
             */
            if(pA==null){
                pA=headB;
            }else {
                pA=pA.next;
            }

            if (pB==null){
                pB=headA;
            }else {
                pB = pB.next;
            }
        }

        return pA;

    }
}
